package com.xbongbong.saas.service.impl;

import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.ddworkbench.pojo.dto.GetPageParameterDTO;
import com.xbongbong.pro.ddworkbench.pojo.vo.ChartPageParameterVO;
import com.xbongbong.pro.ddworkbench.pojo.vo.ListPageParameterVO;
import com.xbongbong.pro.ddworkbench.pojo.vo.StatisticsPageParameterVO;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.TimeTypeEnum;
import com.xbongbong.pro.enums.errorcodes.AppStoreErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.global.ChartCategoryEnum;
import com.xbongbong.pro.enums.workbench.WorkbenchPageEnum;
import com.xbongbong.pro.service.toolbox.statistic.help.ThroughHelp;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.pro.statistic.pojo.TimePojo;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.through.pojo.dto.ThroughDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.service.WorkbenchService;
import com.xbongbong.sys.enums.DataPermissionEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * 创建时间 2021/7/12 9:26 AM
 * 修改时间 2021/7/12 9:26 AM
 * @author chy
 */
@Service("workbenchService")
public class WorkbenchServiceImpl implements WorkbenchService {

    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private ThroughHelp throughHelp;
    @Resource
    private ChartModel chartModel;

    @Override
    public BaseVO getPageParameter(GetPageParameterDTO getPageParameterDTO) throws XbbException {
        UserVO loginUser = getPageParameterDTO.getLoginUser();
        BaseVO baseVO = null;
        String corpid = getPageParameterDTO.getCorpid();
        String pageName = getPageParameterDTO.getPageName();
        WorkbenchPageEnum workbenchPageEnum = WorkbenchPageEnum.getByAlias(pageName);
        switch (workbenchPageEnum) {
            case CUSTOMER_LIST:
                baseVO = getListParam(XbbRefTypeEnum.CUSTOMER, corpid, loginUser);
                break;
            case CONTACT_LIST:
                baseVO = getListParam(XbbRefTypeEnum.CONTACT, corpid, loginUser);
                break;
            case COMMUNICATE_LIST:
                baseVO = getListParam(XbbRefTypeEnum.CUSTOMER_COMMUNICATE, corpid, loginUser);
                break;
            case COMMUNICATE_PLAN_LIST:
                baseVO = getListParam(XbbRefTypeEnum.COMMUNICATE_PLAN, corpid, loginUser);
                break;
            case CONTRACT_LIST:
                baseVO = getListParam(XbbRefTypeEnum.CONTRACT, corpid, loginUser);
                break;
            case PAYMENT_LIST:
                baseVO = getListParam(XbbRefTypeEnum.PAYMENT, corpid, loginUser);
                break;
            case WORK_ORDER_LIST:
                baseVO = getListParam(XbbRefTypeEnum.WORK_ORDER, corpid, loginUser);
                break;
            case WORK_REPORT_LIST:
                baseVO = getListParam(XbbRefTypeEnum.WORK_REPORT, corpid, loginUser);
                break;

            case SALES_BEHAVIOR_ANALYSIS:
                baseVO = getChartParam(corpid, ChartCategoryEnum.SALES_BEHAVIOR_ANALYSIS.getAlias());
                break;
            case CONTRACT_PAYMENT_ANALYSIS:
                baseVO = getChartParam(corpid, ChartCategoryEnum.CONTRACT_RETURN_ANALYSIS.getAlias());
                break;
            case CUSTOMER_ANALYSIS:
                baseVO = getChartParam(corpid, ChartCategoryEnum.CUSTOMER_ANALYSIS.getAlias());
                break;
            case PERFORMANCE_PK:
                baseVO = getChartParam(corpid, ChartCategoryEnum.PK_USER.getAlias());
                break;

            case CUSTOMER_COUNT:
                baseVO = getStatisticsParam(loginUser, SystemCodeEnum.CUSTOMER_ADD_HOME_BOARD);
                break;
            case FOLLOW_CUSTOMER_COUNT:
                baseVO = getStatisticsParam(loginUser, SystemCodeEnum.CUSTOMER_FOLLOW_BOARD);
                break;
            case CONTRACT_COUNT:
                baseVO = getStatisticsParam(loginUser, SystemCodeEnum.CONTRACT_COUNT_BOARD);
                break;
            case CONTRACT_AMOUNT:
                baseVO = getStatisticsParam(loginUser, SystemCodeEnum.CONTRACT_AMOUNT_BOARD);
                break;

        }
        return baseVO;
    }

    /**
     * 列表跳转的参数返回
     * @param xbbRefTypeEnum
     * @param corpid
     * @param userVo
     * @return
     */
    private BaseVO getListParam(XbbRefTypeEnum xbbRefTypeEnum, String corpid, UserVO userVo) throws XbbException {
        PaasMenuEntity paasMenu = paasMenuModel.getByAlias(xbbRefTypeEnum.getAlias(), corpid);
        if (Objects.isNull(paasMenu)) {
            throw new XbbException(AppStoreErrorCodeEnum.API_ERROR_300001, MessageConstant.WORKBENCH_APP_IS_NOT_ENABLED);
        }
        Integer subBusinessType = xbbRefTypeEnum.getCode();
        Integer saasMark =  paasMenu.getSaasMark();
        Long menuId = paasMenu.getId();
        Long appId = paasMenu.getAppId();
        ListPageParameterVO listPageParameterVO = new ListPageParameterVO();
        listPageParameterVO.setSubBusinessType(subBusinessType);
        listPageParameterVO.setSaasMark(saasMark);
        listPageParameterVO.setMenuId(menuId);
        listPageParameterVO.setAppId(appId);
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.COMMUNICATE_PLAN)) {
            listPageParameterVO.setBusinessType(subBusinessType);
            PaasFormEntityExt paasForm = paasFormModel.getByBusinessType(xbbRefTypeEnum.getCode(), corpid);
            listPageParameterVO.setFormId(paasForm.getId());
            listPageParameterVO.setIsAdminOrBoss(userVo.isAdminOrBoss());
        }
        return listPageParameterVO;
    }



    /**
     * 图表参数返回
     * @param corpid
     * @param chartCategoryAlias
     * @return
     */
    private BaseVO getChartParam(String corpid, String chartCategoryAlias) throws XbbException {
        Map<String, Object> parentChartCategoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        parentChartCategoryParam.put("corpid", corpid);
        parentChartCategoryParam.put("alias", chartCategoryAlias);
        parentChartCategoryParam.put("enable", 1);
        parentChartCategoryParam.put("parentId", 0);
        parentChartCategoryParam.put("del", 0);
        List<ChartCategoryEntity> chartCategoryParents = chartCategoryModel.findEntitys(parentChartCategoryParam);
        if (Objects.isNull(chartCategoryParents) || chartCategoryParents.isEmpty()) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224012);
        }
        ChartCategoryEntity parentChartCategory = chartCategoryParents.get(0);

        Map<String, Object> chartCategoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        chartCategoryParam.put("corpid", corpid);
        chartCategoryParam.put("parentId", parentChartCategory.getId());
        chartCategoryParam.put("enable", 1);
        chartCategoryParam.put("del", 0);
        //排序规则：sort降序、id升序
        String sortStr = "sort DESC, id ASC";
        chartCategoryParam.put("orderByStr", sortStr);
        chartCategoryParam.put("start", 0);
        chartCategoryParam.put("pageNum", 1);
        List<ChartCategoryEntity> chartCategorys = chartCategoryModel.findEntitys(chartCategoryParam);
        if (Objects.isNull(chartCategorys) || chartCategorys.isEmpty()) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224012);
        }
        ChartCategoryEntity chartCategory = chartCategorys.get(0);
        Long categoryId = chartCategory.getId();
        Map<String, Object> chartParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        chartParam.put("corpid", corpid);
        chartParam.put("categoryId", categoryId);
        chartParam.put("enable", 1);
        chartParam.put("del", DelEnum.NORMAL.getDel());
        chartParam.put("orderByStr", "sort desc");
        chartParam.put("start", 0);
        chartParam.put("pageNum", 1);

        List<ChartEntity> charts = chartModel.findEntitys(chartParam);
        if (Objects.isNull(charts) || charts.isEmpty()) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224012);
        }
        ChartEntity chart = charts.get(0);
        ChartPageParameterVO chartPageParameterVO = new ChartPageParameterVO();
        chartPageParameterVO.setCategoryId(categoryId);
        chartPageParameterVO.setChartId(chart.getId());
        return chartPageParameterVO;
    }

    private BaseVO getStatisticsParam(UserVO userVo, SystemCodeEnum systemCodeEnum) throws XbbException {
        ChartEntity chartEntity = chartModel.getSystemChartByCode(userVo.getCorpid(), systemCodeEnum);
        if (Objects.isNull(chartEntity)) {
            throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224012);
        }
        ChartResultPojo chartResultPojo = new ChartResultPojo();

        Integer companyStructType = null;
        Long checkedDepId = null;
        String checkedUserId = null;

        Integer dataPermission = userVo.getDataPermission();
        if (Objects.equals(DataPermissionEnum.ALL.getCode(), dataPermission)) {
            companyStructType = 2;
            checkedDepId = 1L;
        } else {
            companyStructType = 1;
            checkedUserId = userVo.getUserId();
        }
        chartResultPojo.setCompanyStructType(companyStructType);
        chartResultPojo.setCheckedDepId(checkedDepId);
        chartResultPojo.setCheckedUserId(checkedUserId);
        chartResultPojo.setChartEntity(chartEntity);
        ThroughDTO throughDto = new ThroughDTO(chartResultPojo, systemCodeEnum);
        TimePojo timePojo = new TimePojo();
        timePojo.setTimeType(TimeTypeEnum.DAY.getCode());

        Long startTimeL = DateTimeUtil.getTodayInt();
        Integer startTime = startTimeL.intValue();
        timePojo.setStartTime(startTime);
        timePojo.setEndTime(startTime + 86400);
        String through = throughHelp.getThrough(throughDto, timePojo);
        StatisticsPageParameterVO statisticsPageParameterVO = new StatisticsPageParameterVO();
        statisticsPageParameterVO.setThrough(through);
        return statisticsPageParameterVO;
    }
}
